import * as echarts from '../../components/ec-canvas/echarts'
Page({
    data: {
        cate_id: '',
        product_common_id: '',
        upAndDownInfo: {},
        ec: {
            // 将 lazyLoad 设为 true 后，需要手动初始化图表
            lazyLoad: true
        },
        active: 0,
    },
    baseOption: {
        color: ['rgb(2, 173, 252)', 'rgb(2, 252, 198)', 'rgb(73, 252, 2)', 'rgb(252, 206, 2)', 'rgb(252, 52, 2)', 'rgb(181, 2, 252)'],
        //图例
        legend: {
            type: 'plain',
            top: 'bottom',
            left: 'center',
            backgroundColor: 'white',
            icon: 'diamond',
            z: 100,
            itemWidth: 15,
            itemHeight: 4,
            itemGap: 12,
        },
        //网格
        grid: {
            left: '34',
            right: '15',
            top: 20,
        },
        //悬浮提示工具
        tooltip: {
            trigger: 'axis',
            confine: true,
            axisPointer: {
                label: {
                    show: true,
                    backgroundColor: '#188075'
                },
            },
        },
        //x轴
        xAxis: {
            axisLine: {
                lineStyle: {
                    show: false,
                    color: '#999',
                }
            },
            axisTick: {
                alignWithLabel: true
            },
            axisLabel: {
                color: '#444',
                hideOverlap: true,
            }
        },
        //y轴
        yAxis: {
            splitLine: {
                show: false,
            },
            min: function(value) {
                let min = value.min - (value.min % 10) - 10
                return min < 0 ? 0 : min;
            },
            axisLine: {
                lineStyle: {
                    type: 'dashed',
                    color: '#aaa',
                }
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#444',
                hideOverlap: true,
            }
        }
    },
    options: [undefined, undefined, undefined],
    onLoad: function(option) {
        const { cate_id, product_common_id, title } = option
        wx.setNavigationBarTitle({
            title
        })
        this.setData({ cate_id, product_common_id, title })
        if (product_common_id) {
            this.request({
                url: `/api/index/rateProduct?product_common_id=${product_common_id}`,
                login: false,
                loadingTip: '加载中',
            }, res => {
                this.setData({ upAndDownInfo: this.format(res.data) })
            })
        } else {
            this.request({
                url: `/api/index/rateCate?cate_id=${cate_id}`,
                login: false,
                loadingTip: '加载中',
            }, res => {
                this.setData({ upAndDownInfo: this.format(res.data) })
            })
        }
    },
    onReady: function() {
        // 获取组件
        this.ecComponent = this.selectComponent('#mychart-dom-bar')
        this.init()
        this.getEchartData()
    },
    // 点击按钮后初始化图表
    init: function() {
        this.ecComponent.init((canvas, width, height, dpr) => {
            // 获取组件的 canvas、width、height 后的回调函数
            // 在这里初始化图表
            const chart = echarts.init(canvas, null, {
                width: width,
                height: height,
                devicePixelRatio: dpr // new
            });

            // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
            this.chart = chart;

            // 注意这里一定要返回 chart 实例，否则会影响事件处理等
            return chart;
        });
    },
    format(value) {
        if (!value) return {}
        if (Number(value.change_rate) === 0) {
            value.isUp = false
            value.upAndDownPrice = 0
            value.change_rate = '-' + value.change_rate
            value.yesterday_price = value.today_price
        } else {
            let upAndDownPrice = Number((value.today_price - Number(value.yesterday_price)).toFixed(2))
            value.isUp = upAndDownPrice > 0
            value.upAndDownPrice = Math.abs(upAndDownPrice)
        }

        return value
    },
    getEchartData() {
        const { cate_id, product_common_id, active } = this.data

        const data = this.options[active]

        if (data != undefined) return this.chart.setOption(this.mergeAttribute(this.baseOption, data))


        this.request({
            url: '/api/index/market',
            login: false,
            loadingTip: '加载中',
            data: {
                cate_id,
                type: [1, 2, 3][active],
                product_common_id
            }
        }, res => {
            let optionData = {
                series: [],
                xAxis: {
                    data: [],
                },
                legend: {
                    data: [],
                },
            }

            Object.keys(res.data).filter(item => {
                return item.endsWith('label')
            }).forEach((key, index) => {
                optionData.legend.data.push(`${res.data[key]}级`)

                let mark = key.split('_')[1]

                let inserObj = {
                    name: `${res.data[key]}级`,
                    type: 'line',
                    smooth: true,
                    data: [],
                }

                let inserObjDataValueObj = res.data[`market_${mark}_items`]

                for (let k in inserObjDataValueObj) {
                    inserObj.data.push(Number(inserObjDataValueObj[k].price))
                    if (optionData.xAxis.data.length === 0) {
                        optionData.xAxis.data = Object.keys(inserObjDataValueObj).map(item => {
                            return item.substring(item.length - 2, item.length) + ['日', '日', '月'][active]
                        })
                    }
                }

                optionData.series.push(inserObj)
            })
            let result = this.mergeAttribute(this.baseOption, optionData)

            this.chart.setOption(result)
            this.options[active] = optionData
        })
    },
    onTabChange(e) {
        const { index } = e.currentTarget.dataset
        if (this.data.active === index) return
        this.setData({ active: index })
        this.getEchartData()
    },
    mergeAttribute(obj1, obj2) {
        let result = JSON.parse(JSON.stringify(obj1))
        for (let key in obj2) {
            if (result.hasOwnProperty(key)) {

                for (let k in obj2[key]) {
                    result[key][k] = obj2[key][k]
                }
            } else {
                result[key] = obj2[key]
            }
        }
        return result
    },
    toPurchase() {
        const { cate_id, product_common_id } = this.data
        if (product_common_id) { //前往产品商品列表
            wx.navigateTo({
                url: `/pages/hall_goods/index?cate_id=${cate_id}&product_common_id=${product_common_id}`,
            })
        } else { //前往改分类交易大厅
            wx.reLaunch({
                url: `/pages/trading_hall/index?id=${cate_id}`,
            })
        }
    },
    onUnload: function() {
        if (this.chart) {
            this.chart.dispose()
        }
        this.baseOption = null
        this.options = null
    }
});